package com.robaone.api.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.robaone.api.business.ActionDispatcher;
import com.robaone.api.data.AppDatabase;
import com.robaone.api.data.Error;
import com.robaone.api.data.SessionData;
import com.robaone.api.json.DSResponse;
import com.robaone.api.json.JSONResponse;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(description = "Handle Login events", urlPatterns = { "/Login" })
public class FormServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FormServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String current_page = request.getParameter("current_page");
		String next_page = request.getParameter("next_page");
		AppDatabase.writeLog("00090: Start Server Side Code:");
		for(int i = 0; i < request.getParameterMap().size();i++){
			Object name = request.getParameterMap().keySet().toArray()[i];
			request.setAttribute(name.toString(), request.getParameterValues(name.toString()));
		}
		SessionData sdata = (SessionData)request.getSession().getAttribute("sessiondata");
		if(sdata == null){
			sdata = new SessionData();
			request.getSession().setAttribute("sessiondata", sdata);
		}
		sdata.setRemoteHost(request.getRemoteHost());
		ActionDispatcher dsp = new ActionDispatcher(sdata,request,response);
		try{
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			String contenttype = dsp.runFormAction(request.getParameterMap(),bout);
			if(contenttype != null){
				response.setContentType(contenttype);
			}
			JSONObject jo = new JSONObject(bout.toString());
			if(jo.getJSONObject("response").getInt("status") == JSONResponse.OK){
				response.sendRedirect(next_page);
			}else if(jo.getJSONObject("response").getInt("status") == JSONResponse.FIELD_VALIDATION_ERROR){
				request.setAttribute("response", jo);
				request.getRequestDispatcher(current_page).forward(request, response);
			}else{
				throw new Exception(jo.getJSONObject("response").getString("error"));
			}
		}catch(Exception e){
			request.setAttribute("error", e.getClass().getName()+": "+e.getMessage());
			request.getRequestDispatcher("error.jsp").forward(request, response);
		}
		
	}

}
